<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use App\Services\WuKongImService;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Http\JsonResponse;
use http\Client\Response;
use Illuminate\Http\Request;

class WukongimController extends Controller
{
    public function send(Request $request)
    {
        try {
            $wukongservice = new WuKongImService();
            $uid = 'admin';
            $wukongservice->reg($uid, 'fdskfkj');
            if ($request->type == 1) {//个人消息
                $req = $wukongservice->sendTo($uid, $request->to_uid, $request->contents);
            } elseif ($request->type == 3) {//站内通知
                $req = $wukongservice->sendTo($uid, $wukongservice::getChannelId(), $request->contents, 2);
            }
        } catch (\Exception $e) {
            return $this->response()->error($e->getMessage());
        }
        if ($req['status'] == 200) {
            return JsonResponse::make()->success('发送成功！')->refresh();
//            return $this->response()->success('发送成功！');
        } else {
            return $this->response()->error('发送失败');
        }
    }

    public function getChannel(Request $request)
    {

        $channel_id = WuKongImService::getChannelId();
        return JsonResponse::make()->success('获取成功！')->data(['channel_id' => $channel_id]);
    }

    public function reg(Request $request)
    {
        $uid = $request->uid;
        $token = $request->token;
        try {
            $wukongservice = new WuKongImService();
            Admin::user()->setAttribute('wkuid', $uid);
            Admin::user()->setAttribute('wktoken', $token);
            $wukongservice->addSubscribers($wukongservice::getChannelId(), [$uid]);
        } catch (\Exception $e) {
            return JsonResponse::make()->error($e->getMessage());
        }
    }
}
